<template>

  <div class="container">
    <el-page-header @back="goBack" content="检验批验收记录">
    </el-page-header>

    <div class="search">
      <span style="line-height: 100%">检验批部位：</span>
      <el-input v-model="inspectPart" placeholder="请输入内容" style="width: 300px"/>
      <span style="line-height: 100%; margin-left: 10px">单位工程：</span>
      <el-input v-model="subprojectName" placeholder="请输入内容" style="width: 300px"/>
      <span style="line-height: 100%; margin-left: 10px">检验批状态：</span>
      <el-select v-model="status" placeholder="请选择检验批状态" style="width: 300px">
        <el-option label="未开始" value="0"/>
        <el-option label="待分发" value="1"/>
        <el-option label="进行中" value="2"/>
        <el-option value="3" label="待审核"/>
        <el-option label="等待第二次采集" value="4"/>
        <el-option label="等待第二次审核" value="5"/>
        <el-option label="审核通过" value="6"/>
        <el-option label="所有状态" value=""/>
      </el-select>
      <el-button type="primary" style="margin-left: 10px;margin-right: 10px" @click="search">搜索</el-button>
      <el-button type="warning" style="margin-left: 10px;margin-right: 10px;" @click="batchExport">批量导出</el-button>
    </div>


    <!-- 检验批验收记录表格 --> <!-- key是保证dom不残留的关键，这个必须不同 -->
    <el-table :data="currentPageData" stripe style="width: 100%; margin-top: 15px"
              @selection-change="handleSelectionChange" row-key="taskId" ref="tableRef"
    >
      <!-- 第一列：多选框 -->
      <el-table-column type="selection" width="55" :reserve-selection="true"/>
      <!-- 第二列：编号 -->
      <el-table-column label="项目号" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.$index + 1 + (currentPage - 1) * pageSize }}
        </template>
      </el-table-column>

      <!-- 固定列：项目名称、单位工程 -->
      <el-table-column prop="projectName" label="工程名称" align="center"/>
      <el-table-column prop="subprojectName" label="单位工程" align="center"/>
      <el-table-column prop="inspectPart" label="检验批部位" align="center"/>
      <el-table-column prop="inspectType" label="检验批名称" align="center"/>
      <el-table-column label="检验批状态" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0">未开始</span>
          <span v-if="scope.row.status === 1">待分发</span>
          <span v-if="scope.row.status === 2">进行中</span>
          <span v-if="scope.row.status === 3">待审核</span>
          <span v-if="scope.row.status === 4">等待第二次采集</span>
          <span v-if="scope.row.status === 5">等待第二次审核</span>
          <span v-if="scope.row.status === 6">审核通过</span>
        </template>
      </el-table-column>

      <!-- 最后一列：操作按钮 -->
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button type="primary" @click="handlePreview(scope.row)">
            预览
          </el-button>
          <el-button type="warning" @click="handleExport(scope.row)">
            导出
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination style="margin-top: 20px; text-align: center" :current-page="currentPage"
                   :page-sizes="[1, 10, 15, 20]" :page-size="pageSize" layout="prev, pager, next, jumper,->,sizes,total"
                   :total="totalData" @size-change="handleSizeChange" @current-change="handleCurrentChange"
    />

  </div>

</template>

<script>
import {
  batchExportInpsectCheckPreview,
  exportInspectCheckPreview,
  search
} from '@/api/statementManage/yanShou/statementManage'

export default {
  data() {
    return {
      status: '',
      inspectPart: '',
      subprojectName: '',   //前三个用来搜索用
      currentPageData: [],   //当前表格数据
      currentPage: 1,
      totalData: 0,
      pageSize: 10,  //上面三个是分页条
      selectedRows: []
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    async search() {
      try {
        console.log(`当前数据为 inspectPart: ${this.inspectPart}, currentPage: ${this.currentPage}, pageSize: ${this.pageSize}, subprojectName: ${this.subprojectName}, status: ${this.status}`)
        const { result } = await search(this.inspectPart, this.currentPage, this.pageSize, this.subprojectName, this.status)
        this.currentPageData = result.list
        this.totalData = Number(result.total) // 给总记录数赋值，及时更改
        console.log('看到我说明接口1成功请求了')
      } catch (e) {
        this.$message.error('获取报表数据失败！')
      }
    },
    handleSizeChange(val) {
      //页面大小变化
      console.log('当前页面大小变化为：' + val)
      this.pageSize = val
      this.search()

    },
    handleCurrentChange(val) {
      //页数变化
      console.log('当前页数变化为：' + val)
      this.currentPage = val
      this.search()
    },
    handleSelectionChange(val) {
      this.selectedRows = val  // 更新选中的行数据
      console.log(this.selectedRows)
    },
    handlePreview(row) {
      //预览报表

      this.previewData = row

      console.log(JSON.stringify(this.previewData)) // 看一下数据有没有传过来呢
      const localStorageId = 'table1' + Date.now() // 生成唯一ID用来本地存储data，因为这个东西需要传递
      localStorage.setItem(localStorageId, JSON.stringify(this.previewData)) // 把数据扔进localstorage

      //this.$router.push({path: '/report-viewer/inspect', query:{localStorageId}})
      switch (row.inspectType) {
        case '模板安装' :
          console.log('触发了模板安装报表预览')
          this.$router.push({ path: '/report-viewer/muban', query: { localStorageId } })
          break
        case '钢筋原材' :
          console.log('触发了钢筋原材报表预览')
          this.$router.push({ path: '/report-viewer/inspect', query: { localStorageId } })
          break
        case '钢筋加工' :
          console.log('触发了钢筋加工报表预览')
          this.$router.push({ path: '/report-viewer/jiagong', query: { localStorageId } })
          break
        case '现浇结构' :
          console.log('触发了现浇结构报表预览')
          this.$router.push({ path: '/report-viewer/xianjiao', query: { localStorageId } })
          break
        case '钢筋连接' :
          console.log('触发了钢筋连接报表预览')
          this.$router.push({ path: '/report-viewer/inspect', query: { localStorageId } })
          break
        case '混凝土拌合物' :
          console.log('触发了混凝土拌合物报表预览')
          this.$router.push({ path: '/report-viewer/inspect', query: { localStorageId } })
          break
        case '混凝土施工' :
          console.log('触发了混凝土施工报表预览')
          this.$router.push({ path: '/report-viewer/inspect', query: { localStorageId } })
          break
        case '钢筋安装' :
          console.log('触发了钢筋安装报表预览')
          this.$router.push({ path: '/report-viewer/anzhuang', query: { localStorageId } })
          break
      }

    },
    async handleExport(row) {
      //导出报表
      try {
        const file = await exportInspectCheckPreview(row.taskId)
        await this.parseFile(file, `inspect_check_${row.taskId}.xls`)
        this.$message.success('导出成功')
      } catch (e) {
        console.error('导出失败:', e)
        this.$message.error('导出失败：' + (e.message || '该报表不可导出'))
      }
    },
    async parseFile(response, defaultFileName) {
      const { downloadFile } = require('@/utils/fileDownload')
      await downloadFile(response, defaultFileName)
    },
    async batchExport() {
      //批量导出
      if (this.selectedRows.length === 0) {
        this.$message.warning('请至少选择一项')
        return
      }
      // 假设你的变量名是 dataArray
      const plainArray = this.selectedRows.slice() // 创建一个新数组副本
      console.log(plainArray)
      const taskIds = this.selectedRows.map(item => item.taskId)
      console.log(taskIds)

      //将这个数组传递给后端，得到一个文件流数组，然后遍历下载
      try {
        const { result } = await batchExportInpsectCheckPreview(taskIds)
        if (result !== undefined || result.length === 0) {
          result.forEach(file => {
            let count = 0
            this.parseFile(file, count++)
          })
        }
      } catch (e) {
        this.$message.error('批量导出失败！')
      }

      //清空多选框
      this.$refs.tableRef.clearSelection()
      this.selectedRows = []
    }
  },
  mounted() {
    this.search()
  }

}
</script>

<style scoped>
.search {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
}

.container {
  margin-top: 10px;
  margin-left: 10px;
}
</style>
